package com.xxwu.springgobang.controller;

import com.xxwu.springgobang.model.User;
import com.xxwu.springgobang.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/userController")
public class UserController {

    @Resource
    private UserService userService;

    //用户登录
    @PostMapping("/login")
    public User login(String username, String password, HttpServletRequest request) {
        //根据名称获取用户信息
        User user = userService.getUserByName(username);
        if (user == null || !user.getPassword().equals(password)) {
            //登陆失败
            log.error("登陆失败");
            return new User();
        }
        //当前若用户首次登陆就没有session
        //当前会话存在就返回session，若不存在就创建
        HttpSession session = request.getSession(true);
        //存储session信息
        session.setAttribute("user", user);
        return user;
    }

    //用户注册
    @PostMapping("/register")
    public User register(String username, String password) {
        if(username == "" || password == "") {
            return new User();
        }
        User user = new User();
        try{
            user.setUsername(username);
            user.setPassword(password);
            log.info("user:{}", user);
            int ret = userService.insert(user);
            log.info("ret:{}", ret);
        } catch (DuplicateKeyException e){
            user = new User();
        }
        log.info("user:{},userId{}",user, user.getUserId());
        return user;
    }

    //查询用户信息
    @GetMapping("/getUserInfo")
    public User getUserInfo(HttpServletRequest request) {
        User user;
        try{
            //这里已经不是首次登陆了，无需创建session
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute("user");
            // 后续要实现更新数据的操作，若根据上述逻辑那么客户端显示的一直都是登陆时查询到的数据，这里要对数据进行更新
            User newUser = userService.getUserByName(user.getUsername());
            return newUser;
        }catch (NullPointerException e){
            user = new User();
            return user;
        }
    }
}
